package com.juku2024.juku.tools

import android.text.TextUtils
import android.util.Log
import com.juku2024.juku.base.BaseApplication
import java.math.BigDecimal
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap


object AnalysisUtils {


    fun analysis(event: String, key: String?) {
        if (TextUtils.isEmpty(key)) return
        Log.d("analysis","$event -> $key")
    }

    fun analysis(event: String, key: String, value: Any?) {
        if (value == null) return
        val map = HashMap<String, Any>()
        map[key] = value
        Log.d("analysis","$event -> $map")
    }


    fun analysis(event: String, params: Map<String, Any?>) {
        Log.d("analysis","$event -> $params")
    }


    fun getTimeRange(duration: Long): String {
        val timeRange: String
        // 超过20s
        if (duration >= 30000) {
            timeRange = "30s+"
        } else {
            /**
            当前最多1000个取值，需要将duration放置到对应的取值范围中
            最终展现形式
            0-30ms
            30-60ms
            60-90ms
            ....
            990-1200ms
            1.2-1.5s
             */

            // 最小单位 30ms
            val i = duration / 30
            val start = i * 30
            val end = (i + 1) * 30
            timeRange = if (start < 1000) {
                val rangeFormat = "%d-%d%s"
                String.format(rangeFormat, start, end, "ms")
            } else {
                val rangeFormat = "%s-%s%s"
                val startD = roundValue((start / 1000f).toDouble())
                val endD = roundValue((end / 1000f).toDouble())
                String.format(rangeFormat, startD, endD, "s")
            }
        }
        return timeRange
    }

    /**
     * 提供精确的小数位四舍五入处理
     *
     * @param v 需要四舍五入的数字
     * @param scale 小数点后保留几位
     * @return 四舍五入后的结果
     */
    @Suppress("DEPRECATION")
    private fun roundValue(v: Double): String {
        val b = BigDecimal(v)
        return b.setScale(2, BigDecimal.ROUND_HALF_UP).toString()
    }

    fun getDurationTime(duration: Long): String{
        // 0-5，6-15,16-30， 30+
        val second = duration / 1000
        return when (second) {
            in 0..1 -> {
                "0-1"
            }
            in 2..5 -> {
                "2-5"
            }
            in 5..10 -> {
                "5-10"
            }
            in 10..30 -> {
                "10-30"
            }
            else -> {
                "30+"
            }
        }
    }
}